<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { getFavoriteListApi, postCancelFavoriteApi } from '@/api/favorite'
import { fullUrl } from '@/utils/common'
import type { favoriteItem } from '@/types/favorite'
import { onShow } from '@dcloudio/uni-app'
import { safeBottom, pageUrl } from '@/utils/constants'

// eslint-disable-next-line no-undef
const paging = ref<ZPagingInstance>()
const dataList = ref<favoriteItem[]>([])
const queryList = (page: number, page_size: number) => {
  getFavoriteListApi({ page, page_size }).then((res) => {
    paging.value?.complete(res.result.data)
  })
}

const swipeActionRef = ref()
const rightOptions: UniHelper.UniSwipeActionItemOption[] = [
  {
    text: 'Remove',
    style: {
      backgroundColor: '#F4333C',
      color: '#fff',
      fontSize: '20',
    },
  },
]
const onClickFavoriterItem = (
  event: UniHelper.UniSwipeActionItemOnClickEvent,
  item: favoriteItem,
) => {
  switch (event.index) {
    case 0:
      return onCancelFavorite(item.goods_id)
  }
}
const onCancelFavorite = async (id: string | number, is_all: boolean = false) => {
  uni.showModal({
    title: 'Tip',
    content: 'Are you sure you want to remove this from favorites?',
    success: (res) => {
      if (res.confirm) {
        postCancelFavoriteApi({ goods_id: id, is_all }).then(() => {
          paging.value?.refresh()
          setTimeout(() => {
            uni.showToast({
              title: 'Successfully removed from favorites',
              icon: 'none',
            })
          }, 500)
        })
      }
    },
  })
}

//全选状态
const isCheckdedAll = ref(false)
//底部按钮禁用状态
const isDisabledCancelChecked = computed(() => !dataList.value.some((item) => item.checked))

const onChecked = (index: number) => {
  const item = dataList.value[index]
  item.checked = !item.checked
}

const onCheckedAll = () => {
  const checkded = isCheckdedAll.value
  dataList.value = dataList.value.map((item) => ({ ...item, checked: !checkded }))
}

const onCancelAllFavorite = () => {
  const checkdedIds = dataList.value
    .filter((item) => item.checked)
    .map((item) => item.goods_id)
    .join(',')

  if (!checkdedIds) {
    return uni.showToast({
      title: 'Please select products first',
      icon: 'none',
    })
  }

  onCancelFavorite(checkdedIds, isCheckdedAll.value)
}

// 监听 dataList 的变化，更新全选状态
watch(
  dataList,
  (newList) => {
    if (newList.length > 0) {
      isCheckdedAll.value = newList.every((item) => item.checked)
    } else {
      isCheckdedAll.value = false
    }
  },
  { deep: true },
)

onShow(() => {
  paging.value?.refresh()
})
</script>

<template>
  <z-paging
    ref="paging"
    v-model="dataList"
    @query="queryList"
    :use-page-scroll="true"
    empty-view-text="No favorites yet. Start shopping now!"
    :safe-area-inset-bottom="true"
    :paging-style="{
      backgroundColor: '#f7f7f8',
    }"
  >
    <view class="panel">
      <uni-swipe-action class="section" ref="swipeActionRef">
        <uni-swipe-action-item
          v-for="(item, index) in dataList"
          :key="index"
          :right-options="rightOptions"
          @click="onClickFavoriterItem($event, item)"
        >
          <view class="goods-item">
            <view class="checkbox" :class="{ checked: item.checked }" @tap="onChecked(index)" />
            <navigator
              class="goods"
              hover-class="none"
              :url="`${pageUrl['goods-detail']}?id=${item.goods_id}`"
            >
              <image class="image" :src="fullUrl(item.images[0])" />
              <view class="info">
                <view class="name ellipsis">{{ item.name }}</view>
                <view class="price">
                  <view class="now">
                    <text class="symbol">$</text>
                    <text class="number">{{ item.min_price }}</text>
                  </view>
                </view>
              </view>
            </navigator>
          </view>
        </uni-swipe-action-item>
      </uni-swipe-action>
    </view>
    <template #bottom>
      <view class="toolbar" :style="safeBottom">
        <text class="all" :class="{ checked: isCheckdedAll }" @tap="onCheckedAll">Select All</text>
        <view class="button-grounp">
          <view
            class="button sub-button"
            :class="{ disabled: isDisabledCancelChecked }"
            @tap="onCancelAllFavorite"
          >
            Remove
          </view>
        </view>
      </view>
    </template>
  </z-paging>
</template>

<style scoped lang="scss">
.panel {
  margin: 20rpx 20rpx;
}

.goods-item {
  padding: 20rpx;
  background: #fff;
  margin-bottom: 20rpx;
  border-radius: 10rpx;
}

.goods {
  width: 100%;
  display: flex;
  margin-left: 40rpx;
}
.image {
  width: 150rpx;
  height: 150rpx;
  margin-right: 10rpx;
}
.info {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  width: 70%;
}
.name {
  font-size: 24rpx;
}
.ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
}
.price {
  display: flex;
  flex-direction: column;
  margin-top: 10rpx;
  .origin {
    font-size: 22rpx;
    margin-right: 10rpx;
    text-decoration: line-through;
  }
  .now {
    color: red;
  }
  .symbol {
    // font-size: 18rpx;
  }
}

.checkbox {
  position: absolute;
  top: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 60rpx;
  height: 100%;

  &::before {
    content: '\e6cd';
    font-family: 'iconfont' !important;
    font-size: 40rpx;
  }

  &.checked::before {
    content: '\e6cc';
    color: #ff5f3c;
  }
}

.toolbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: var(--window-bottom);
  z-index: 100;

  height: 100rpx;
  display: flex;
  align-items: center;
  border-top: 1rpx solid #ededed;
  border-bottom: 1rpx solid #ededed;
  background-color: #fff;
  box-sizing: content-box;

  .all {
    margin-left: 15rpx;
    font-size: 15px;
    color: #444;
    display: flex;
    align-items: center;
  }

  .all::before {
    font-family: 'iconfont' !important;
    content: '\e6cd';
    font-size: 40rpx;
    margin-right: 8rpx;
  }

  .checked::before {
    content: '\e6cc';
    color: #ff5f3c;
  }

  .text {
    margin-right: 8rpx;
    margin-left: 12rpx;
    color: #444;
    font-size: 14px;
  }

  .button-grounp {
    margin-left: auto;
    display: flex;
    justify-content: space-between;
    text-align: center;
    line-height: 72rpx;
    font-size: 13px;
    color: #fff;

    .button {
      width: 240rpx;
      margin: 0 10rpx;
      border-radius: 72rpx;
      display: inline-block;
      text-align: center;
    }

    .sub-button {
      background-color: #ff5f3c;

      &.disabled {
        opacity: 0.6;
      }
    }
  }
}
</style>
